<?php

namespace backend\models;

use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "permission".
 *
 * @property int $id
 * @property string $name 名称
 * @property int $menu_code 菜单权限code
 * @property int $btn_code 按钮权限code
 * @property int $status 1正常,2禁用
 * @property string $parent_id 父级id, 1顶级菜单
 * @property int $level 级别 1顶级菜单 2子集菜单 3操作
 * @property string $create_time 创建时间
 */
class PermissionModel extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'permission';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['parent_id', 'level', 'create_time', 'menu_code', 'btn_code','status'], 'integer'],
            [['name'], 'string', 'max' => 64],
            [['url'], 'string'],
            [['name', 'level', 'parent_id'],'required', 'on' => ['add'],'message'=>'{attribute}不能为空！'],
            [['name', 'level', 'parent_id','id'],'required', 'on' => ['edit'],'message'=>'{attribute}不能为空！'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '名称',
            'menu_code' => '菜单权限code',
            'btn_code' => '按钮权限code',
            'url' => '路由',
            'status' => '1正常,2禁用',
            'parent_id' => '父级id, 1顶级菜单',
            'level' => '级别 1顶级菜单 2子集菜单 3操作',
            'create_time' => '创建时间',
        ];
    }

    /**
     * 保存前
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert)){
            if($this->isNewRecord){
                $this->create_time = time();
                $this->status = 1;
            }
            return true;
        }
        return false;
    }

    /*
     * 获取所有
     */
    public static function AllMenu()
    {
        $list = self::find()->select(['id','name'])->where(['status'=>1])->orderBy('id asc')->asArray()->all();
        $list = ArrayHelper::map($list,'id','name');
        return $list;
    }

    public static function levelList($id=0,$parent_id='')
    {
        $list = self::find()->select(['id','menu_code','btn_code','name','level','parent_id','url'])->where(['status'=>1])->orderBy('id asc')->asArray()->all();
        $one = $two = $three = [];
        if(!empty($list)){
            foreach ($list as $key => $value){
                $value['is_selected'] = 0;
                $value['code'] = !empty($value['menu_code']) ? $value['menu_code'] : $value['btn_code'];
                if($id){
                    if($value['id'] == $id){
                        $value['is_selected'] = 1;
                    }
                }
                if($value['level'] == 1){
                    unset($value['btn_code']);
                    $one[] = $value;
                }
                if($value['level'] == 2){
                    unset($value['btn_code']);
                    $two[] = $value;
                }
                if($value['level'] == 3){
                    $value['menu_code'] = $value['btn_code'];
                    unset($value['btn_code']);
                    $three[] = $value;
                }
            }
        }
        $two = self::resetArray($two,$three);
        $one = self::resetArray($one,$two);
        if($id){
            $res[] = self::getSelectCode($one,1);
            if($parent_id != 0) {
                $res = self::reset($res, $one);
            }
            return $res;
        }
        return $one;
    }

    //无限极
    public static function reset($res,$v)
    {
        if ($v) {
            foreach ($v as $k => $val) {
                if (isset($val['is_selected']) && $val['is_selected'] == 1 && !empty($val['child'])) {
                    $res[] = self::getSelectCode($val['child']);
                }
                if (!empty($val['child'])) {
                    $res = self::reset($res, $val);
                }
            }
        }
        return $res;
    }

    //组装数据
    public static function resetArray($list,$res)
    {
        if(!empty($list)){
            foreach ($list as $key => $value){
                if(!empty($res)){
                    foreach ($res as $k => $val){
                        if($value['id'] == $val['parent_id']){
                            if(isset($val['is_selected']) && $val['is_selected'] ==1){
                                $list[$key]['is_selected'] = 1;
                            }
                            $list[$key]['child'][] = $val;
                        }
                    }
                }
            }
        }
        return $list;
    }


    /**
     * 获取顶级菜单
     */
    public static function getParentList($is_select=false,$parent_id=0)
    {
        $list = [];
        $res = self::find()->select('id,name')->where('status=1 AND parent_id='.$parent_id)->andWhere(['!=','level',3])->asArray()->all();
        if($res){
            $count = count($res)-1;
            foreach($res as $key=>$val){
                $list[$val['id']] = ($is_select?($count == $key ?'└ ':' ├ '):'').$val['name'];
            }
        }
        return $list;
    }



    private static function getSelectCode($ret,$flag=0)
    {
        $select = '';
        if($ret){
            $select .= "<select class='form-control menu_class' name='PermissionModel[parent_id]'>";
            if($flag == 1){
                $select .= "<option value='0'>顶级菜单</option>";
            }else {
                $select .= "<option value=''>请选择</option>";
            }
            foreach($ret as $item){
                $select .= "<option ".($item['is_selected'] == 1 ? "selected":"")." value='{$item['id']}'>{$item['name']}</option>";
            }
            $select .= "</select>";
        }
        return $select;
    }
}